/**
 * 
 * @param {function((object)=>Promise,(object)=>Promise)} fn 
 */
function Promise(fn){
    const PADDING="PADDING",FULFILLED="FULFILLED",REJECTED="REJECTED";

    this.returnPromise = [];
    this.successCallback = [];
    this.failCallback=[];
    this.state = PADDING;
    
    function resolve(result){
        if(this.state != PADDING) return;

        this.state = FULFILLED;

        this.successCallback.forEach(function(fn){
            let back = fn(result)
        });
    }

    function reject(error){
        this.state = REJECTED;
        this.failCallback.forEach(function(fn){
            let back = fn(error);
        });
    }

    function createPromise(back){
        if(back instanceof Promise && typeof back.then === "function"){
            return back;
        }else{
            return new Promise(function(resolve){resolve(back)});
        }
    }

    this.then = function(success,fail){
        switch (this.state){
            case FULFILLED:
                createPromise(success(this.result));
                break;
            case REJECTED:
                createPromise(fail(this.error));
                break;
            default:
                this.successCallback.push(success);
                if(fail){
                    this.failCallback.push(fail)
                }
                break;
        }
        return new Promise((resolve)=>{

            resolve
        });
    }
    this.catch = function(fail){
        this.failCallback.push(fail)
    }
    fn(resolve,reject);
}